import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:open_filex/open_filex.dart';
import 'package:safetymonitor/app/components/photo_show.dart';
import 'package:safetymonitor/app/components/toast_widget.dart';
import 'package:safetymonitor/app/components/video/ijk_player.dart';
import 'package:safetymonitor/app/core/utils/interface.dart';
import 'package:path_provider/path_provider.dart';
import 'package:safetymonitor/generated/assets.dart';

class FileUtils {
  /// 获取文件类型
  static String? getFileType(String path) {
    if (path.isEmpty) {
      return null;
    }
    final int index = path.lastIndexOf('.');
    if (index == -1) {
      return null;
    }
    return path.substring(index + 1);
  }

  /// 根据文件类型打开文件
  /// [path] 文件路径 可以自动判断是否有http
  /// [title] 标题
  static openFile(String? path, {String? title}) {
    if (path == null || path.isEmpty) {
      AppToast.showWarning('暂无文件!');
      return;
    }
    final String? type = getFileType(path);
    if (type == null) {
      return null;
    }
    if (!path.startsWith('http')) {
      path = '${Interface.fileUrl}$path';
    }

    // 判断是不是内网中
    if(Interface.fileUrl != 'http://192.168.50.67:9090') {
      if(path.startsWith('http://172.13.200.20')) {
        // 把开头 http://172.13.200.20 ，则替换为 http://219.145.189.219
        path = path.replaceFirst('http://172.13.200.20:9090', 'http://219.145.189.219:9090');
      }
    }


    switch (type) {
      case 'pdf' || 'PDF':
        return downloadFile(path, type: 'application/pdf');
      case 'doc':
        return downloadFile(path, type: 'application/msword');
      case 'docx':
        return downloadFile(path, type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
      case 'xls':
        return downloadFile(path, type: 'application/vnd.ms-excel');
      case 'xlsx':
        return downloadFile(path, type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
      case 'ppt':
        return downloadFile(path, type: 'application/vnd.ms-powerpoint');
      case 'pptx':
        return downloadFile(path, type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation');
      case 'txt':
        return downloadFile(path);
      case 'apk':
        return downloadFile(path, type: 'application/vnd.android.package-archive');
      case 'jpg' || 'jpeg' || 'png' || 'gif' || 'jfif' || 'webp':
        return Get.to(() => PhotoShowPage(url: path!, title: title));
      case 'mp4' || 'avi':
        return Get.to(() => IjkPlayerPage(
              url: path!,
              title: path.toString(),
            ));
      default:
        return downloadFile(path);
    }
  }

  //根据下载路径获取保存的文件路径
  static Future<String> getSavePath(String url) async {
    final filename = url.substring(url.lastIndexOf('/') + 1);
    // 替换为你要保存的文件路径
    final Directory directory = await getApplicationDocumentsDirectory();
    final String savePath = '${directory.path}/$filename';
    return savePath;
  }

  /// 从网络上下载文件
  static Future<String> downloadFile(
    String url, {
    String? type,
    bool isOpen = true,
    Function(int, int)? onReceiveProgress,
    bool isShowLoading = true,
        Function(Object e)? onError,
  }) async {
    final String savePath = await getSavePath(url);

    if (!isOpen) {
      return savePath;
    }

    ///  扫描文件是否存在  [isExist]为true存在，为false不存在
    final bool isExist = await File(savePath).exists();
    // 不存在就下载 存在就直接打开
    if (isExist) {
      if (isOpen) {
        OpenFilex.open(savePath, type: type,).catchError((e) {
          print('open file error: $e');
        });
      }
      return savePath;
    }
    if (isShowLoading) {
      SmartDialog.showLoading(msg: '正在下载...');
    }

    try {
      await Dio(BaseOptions(
        //连接服务器超时时间，单位是毫秒.
        connectTimeout: const Duration(seconds: 3),
        // 响应流上前后两次接受到数据的间隔，单位为毫秒。
        receiveTimeout: const Duration(seconds: 3),
      )).download(url, savePath, onReceiveProgress: onReceiveProgress);
    } on DioException catch (e) {
      if (e.response != null && e.response!.statusCode == 404) {
        // Handle 404 error
        // print('404 Not Found: ${e.message}');
        // 执行特定于处理 404 错误的操作，例如向用户显示消息
        //   AppToast.showError('${e.response?.statusMessage}');
        AppToast.showError('未找到资源~');
      } else {
        // Handle other DioError exceptions
        // print('Request failed with error: ${e.message}');
        AppToast.showError('${e.message!.contains('The request connection took longer than')?'请求服务器超时~':e.message}');
      }
    }

    if (isShowLoading) {
      SmartDialog.dismiss();
    }
    if (isOpen) {
      OpenFilex.open(savePath, type: type);
    }
    return savePath;
  }

  /// 删除文件
  static Future delete(String? url) async {
    if (url == null) {
      return;
    }
    final String? type = getFileType(url);
    if (type == null) {
      return null;
    }
    final String filename = url.substring(url.lastIndexOf('/') + 1);
    // 替换为你要保存的文件路径
    final Directory directory = await getApplicationDocumentsDirectory();
    final String savePath = '${directory.path}/$filename';
    File(savePath).delete();
  }

  static SvgPicture getIcon(
    String filename, {
    double? width,
    double? height,
    String? ext,
  }) {
    final path = switch (filename.split('.').lastOrNull ?? ext) {
      'pdf' => Assets.svgFilePdf,
      'doc' || 'docx' => Assets.svgFileWord,
      'xls' || 'xlsx' => Assets.svgFileExcel,
      'ppt' || 'pptx' => Assets.svgFilePpt,
      'txt' => Assets.svgFileTxt,
      'png' || 'jpg' || 'jpeg' || 'gif' || 'jfif' || 'webp' => Assets.svgFileImg,
      _ => Assets.svgFileCode,
    };
    return SvgPicture.asset(
      path,
      width: width,
      height: height,
    );
  }
}
